<template>
    <view class="land-selector-container">
        <view
            style="
                display: flex;
                justify-content: space-between;
                align-items: center;
            "
        >
            <view class="section-title">选择地块</view>
            <view class="all-select" v-if="multiple">
                <checkbox
                    :checked="allSelected"
                    :color="checkboxColor"
                    @click="toggleAll"
                ></checkbox>
                <text>全选</text>
            </view>
        </view>

        <view class="land-grid">
            <view
                v-for="(item, index) in lands"
                :key="index"
                :class="['land-item', { active: item.selected }]"
                @click="selectLand(index)"
            >
                <image
                    src="/static/images/cao.png"
                    mode="aspectFill"
                ></image>
                <text>{{ item.name }}</text>
            </view>
        </view>
    </view>
</template>

<script>
import { mapState, mapGetters, mapActions } from 'vuex';

export default {
    name: "LandSelector",
    props: {
        checkboxColor: {
            type: String,
            default: "#4062F6",
        },
        multiple: {
            type: Boolean,
            default: false,
        }
    },
    emits: ['selection-change'],
    data() {
        return {
            lands: [],
        };
    },
    created() {
        this.initLocalData();
    },
    computed: {
        ...mapGetters(['getParcelData', 'getParcelLoading']),
        allSelected() {
            return (
                this.lands.length > 0 &&
                this.lands.every((land) => land.selected)
            );
        },
        selectedLands() {
            return this.lands.filter((land) => land.selected);
        },
    },
    methods: {
        ...mapActions(['fetchParcelData']),
        // 初始化本地数据
        async initLocalData() {
            // 获取 store 中的数据
            const data = await this.fetchParcelData();
            this.formatAndSetData(data);
        },
        
        // 格式化并设置数据
        formatAndSetData(data) {
            if (data && data.length > 0) {
                this.lands = data.map((parcel) => ({
                    id: parcel.id,
                    name: parcel.parcelName,
                    selected: false,
                }));
            } else {
                this.initDefaultData();
            }
        },

        // 刷新数据
        async refreshData() {
            try {
                uni.showLoading({ title: "刷新地块数据..." });
                const data = await this.fetchParcelData(true); // 强制刷新
                this.formatAndSetData(data);
                uni.hideLoading();
            } catch (error) {
                console.error("刷新地块数据失败", error);
                uni.hideLoading();
                uni.showToast({
                    title: "刷新地块数据失败",
                    icon: "none",
                });
            }
        },

        initDefaultData() {
            // 默认数据，当API请求失败时使用
            this.lands = [
                {
                    id: null,
                    name: "空地块",
                    selected: false,
                },
            ];
        },

        selectLand(index) {
            if (!this.multiple) {
                // 单选模式：先清除所有选中状态，再选中当前项
                this.lands.forEach(land => land.selected = false);
                this.lands[index].selected = true;
            } else {
                // 多选模式：切换选中状态
                this.lands[index].selected = !this.lands[index].selected;
            }
            this.$emit('selection-change', this.selectedLands);
        },
        
        toggleAll() {
            const newValue = !this.allSelected;
            this.lands.forEach((land) => (land.selected = newValue));
            this.$emit('selection-change', this.selectedLands);
        },
        
        // 获取选中的地块
        getSelectedLands() {
            return this.selectedLands;
        },
        
        // 验证是否有选中的地块
        validate() {
            return this.lands.some((land) => land.selected);
        },
        
        // 设置选中状态
        setSelectedLands(idString) {
            if (!idString) return;
            
            const idArray = idString.split(',');
            
            this.lands.forEach(item => {
                item.selected = idArray.includes(item.id.toString());
            });
        },
    },
};
</script>

<style lang="scss" scoped>
.land-selector-container {
    background-color: #fff;
    margin-bottom: 20rpx;

    .section-title {
        font-size: 32rpx;
        font-weight: 500;
        color: #333;
        margin-bottom: 20rpx;
    }

    .all-select {
        display: flex;
        align-items: center;
        margin-bottom: 20rpx;

        checkbox {
            margin-right: 10rpx;
            transform: scale(0.8);
        }

        text {
            font-size: 26rpx;
            color: #666;
        }
    }

    .land-grid {
        display: flex;
        flex-wrap: wrap;
        margin: 0 -10rpx;

        .land-item {
            width: calc(25% - 20rpx);
            margin: 10rpx;
            position: relative;
            border-radius: 8rpx;
            height: 132rpx;
            font-family: OPPOSans, OPPOSans;
            font-weight: 400;
            font-size: 24rpx;
            color: #333333;
            text-align: center;
            background: rgba(227, 227, 227, 0.35);

            image {
                width: 76rpx;
                height: 96rpx;
                margin-top: -20rpx;
                object-fit: cover;
            }

            text {
                position: absolute;
                bottom: 0;
                left: 0;
                right: 0;
                text-align: center;
                padding: 8rpx 0;
            }

            &.active {
                background: #1f41da;
                color: #ffffff;
            }
        }
    }
}
</style>
